﻿using System;
using System.IO;
using System.Drawing;
using System.Linq;

namespace FxCore.Base
{
    /// <summary>
    /// 瓦片的图片实体
    /// </summary>
    public class FxImage
    {
        public string Type { get; }

        public static FxImage Empty;

        private readonly byte[] _content;

        static FxImage()
        {
            Empty = new FxImage();
        }

        private FxImage()
        {
            //禁止使用new实例化
            this.Type = String.Empty;
            this._content = null;
        }

        private FxImage(string type, byte[] content)
        {
            if (string.IsNullOrEmpty(type))
            {
                throw new ArgumentException();
            }

            this.Type = type;
            this._content = content;
        }

        public FxImage FromStream(string type, Stream content)
        {
            MemoryStream ms = new MemoryStream();
            content.CopyTo(ms);
            
            return new FxImage(type, ms.ToArray());
        }

        public FxImage FromBytes(string type, byte[] content)
        {
            return new FxImage(type, content);
        }

        public void Save(string path)
        {
            if (string.IsNullOrEmpty(path))
            {
                throw new ArgumentException();
            }

            path = Path.HasExtension(path) ? path : $"{path}.{this.Type}";
            Image image = Image.FromStream(new MemoryStream(this._content));

            image.Save(path);
        }

        public override bool Equals(object obj)
        {
            FxImage image = (FxImage) obj;
            if (image == null)
            {
                throw new NullReferenceException();
            }

            return this._content.SequenceEqual(image._content);
        }

        public override int GetHashCode()
        {
            return this._content.GetHashCode();
        }
    }
}
